import fetch from 'dva/fetch';


//const host="http://119.29.59.214/IBaseUser/"
// const host="http://api.wyd723.cn/"
const host = "http://localhost:7001/api/v1/"

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export  function requestJSON(url, options) {
  let pack={url:url,options:options};
  base(pack);
  beforeJSON(pack.options);
  return fetch(pack.url,pack.options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => ({ data }))
    .catch(err => ({ err }));
}

export  function requestForData(url, options) {
  let pack={url:url,options:options};
  base(pack);
  before(pack.options);
  return fetch(pack.url,pack.options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => ({ data }))
    .catch(err => ({ err }));
}

export  function request(url, options) {
  let pack={url:url,options:options};
  base(pack);
  return fetch(pack.url,pack.options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => ({ data }))
    .catch(err => ({ err }));
}

function before(options){
  let headers= {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded',},
  };

  Object.assign(options,headers,JSONtoForData(options['body']));
}

function beforeJSON(options){
  //  let headers= {
  //   headers: { 'Content-Type': 'application/json',},
  // };

  Object.assign(options,JSONtoForData(options['body']));
}

function JSONtoForData(data){
    //let fData=new FormData();
    let fData=[];
     for(let key in data){
       //fData.append(key,data[key]);
       fData.push(`${key}=${data[key]}`);
    }

    return {body:fData.join("&")};
}

function base(pack){
 pack.url=host+pack.url;
 cookie(pack.options);
 get(pack);
}

function get(pack){
  if(pack.options.method=="GET"){
    if(pack.options.hasOwnProperty("body")){
      let data=pack.options.body;
      let fData=[];
      for(let key in data){
        //fData.append(key,data[key]);
        fData.push(`${key}=${data[key]}`);
      }

      pack.url+="?"+fData.join("&");
    }
  }

}
function cookie(options){
   Object.assign(options,{credentials: 'include',mode: 'cors'});
}
